package dongze.com.ckdj.activity.custom;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import dongze.com.ckdj.R;
import dongze.com.ckdj.activity.AddMassLossRecordActivity;
import dongze.com.ckdj.activity.ProgressableActivity;
import dongze.com.ckdj.databinding.MassLossPictureItemBinding;
import dongze.com.ckdj.databinding.model.MassLossImageItemModel;
import dongze.com.ckdj.util.Util;

/**
 * Created by fanqwz on 2017/12/20.
 */

public class MartinPhotoCheckInActivity extends ProgressableActivity {
    private static final int IMAGE_COUNT = 6;
    private static final int PHOTO_INTENT = 1025;
    private static final String IMAGE_PRIFIX = "martin";
    @BindView(R.id.mass_loss_image_grid)
    GridLayout mGlImage;
    @BindView(R.id.vin)
    TextView vinTextView;
    @BindView(R.id.key)
    TextView keyTextView;

    MassLossImageItemModel[] imageModels = new MassLossImageItemModel[IMAGE_COUNT];
    File[] capturedImage = new File[IMAGE_COUNT];

    private String vin;
    private String key;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vin = getIntent().getStringExtra("vin");
        key = getIntent().getStringExtra("key");

        if (TextUtils.isEmpty(vin)) {
            Toast.makeText(this, "车架号不能为空", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        if (TextUtils.isEmpty(key)) {
            Toast.makeText(this, "项目不能为空", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        setContentView(R.layout.martin_photo_check_in);
        ButterKnife.bind(this);
        vinTextView.setText(vin);
        keyTextView.setText(key);
        buildMassLossImage();

        String value = getIntent().getStringExtra("value");
        List<Pair<Integer, String>> arr = new Gson().fromJson(value, new TypeToken<List<Pair<Integer, String>>>() {}.getType());
        if (arr != null && arr.size() > 0) {
            for (Pair<Integer, String> p : arr) {
                File f = new File(p.second);
                if (f.exists()) {
                    capturedImage[p.first] = f;
                    imageModels[p.first].setImageFile(f.getAbsolutePath());
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.martin_photo_check_in, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (R.id.save == item.getItemId()) {
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void finish() {
        List<Pair<Integer, String>> list = new ArrayList<>(capturedImage.length);
        for (int i = 0; i < capturedImage.length; i++) {
            if (capturedImage[i] == null)
                continue;

            list.add(new Pair<>(i, capturedImage[i].getAbsolutePath()));
        }

        if (list.size() > 0) {
            Intent intent = new Intent();
            intent.putExtra("key", key);
            intent.putExtra("value", new Gson().toJson(list));
            setResult(Activity.RESULT_OK, intent);
        } else {
            setResult(RESULT_CANCELED);
        }

        super.finish();
    }

    // 照片网格
    private void buildMassLossImage() {
        for (int i = 0; i < IMAGE_COUNT; i++) {
            final int value = i;
            final MassLossImageItemModel image = new MassLossImageItemModel();
            image.setOnNewClicked(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!Util.checkCapturePermission(MartinPhotoCheckInActivity.this))
                        return;

                    File file = Util.getImageFile(IMAGE_PRIFIX);

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
                    if (currentapiVersion < 24) {
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                        startActivityForResult(intent, PHOTO_INTENT + value);
                    } else {
                        Uri uri = FileProvider.getUriForFile(MartinPhotoCheckInActivity.this, "dongze.com.ckdj.fileprovider", file);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        startActivityForResult(intent, PHOTO_INTENT + value);
                    }
                    capturedImage[value] = file;
                }
            });
            image.setOnDeleteClicked(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    image.setImageFile(null);
                    Util.deleteFile(capturedImage[value].getAbsolutePath());
                    capturedImage[value] = null;
                }
            });
            image.setOnImageClicked(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Util.ViewImage(MartinPhotoCheckInActivity.this, capturedImage[value]);
                }
            });
            imageModels[i] = image;

            MassLossPictureItemBinding binding1 = DataBindingUtil.inflate(getLayoutInflater(), R.layout.mass_loss_picture_item, mGlImage, false);
            binding1.setMassLossImageItem(imageModels[i]);
            int width = getResources().getDisplayMetrics().widthPixels / 3-
                    getResources().getDimensionPixelSize(R.dimen.content_padding);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams(new ViewGroup.LayoutParams(
                    width, width));
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                params.columnSpec = GridLayout.spec(i % 3, 1f);
//                params.rowSpec = GridLayout.spec(i / 3, 1f);
//            }

            Log.d("111", "buildMassLossImage: " + (i % 3) + "," + (i / 3));
            mGlImage.addView(binding1.getRoot(), params);
        }
        mGlImage.requestLayout();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode >= PHOTO_INTENT && requestCode <= PHOTO_INTENT + IMAGE_COUNT) {
            int offset = requestCode - PHOTO_INTENT;
            if (resultCode == RESULT_OK) {

                if (!capturedImage[offset].exists())
                    return;

//            try {
//                BitmapFactory.Options o = new BitmapFactory.Options();
//                o.inSampleSize = 2;
//                Bitmap b = BitmapFactory.decodeFile(capturedImage[offset].getAbsolutePath(), o);
//                imageModels[offset].setImageFile(new BitmapDrawable(getResources(), b));
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
                imageModels[offset].setImageFile(capturedImage[offset].getAbsolutePath());
            } else {
                capturedImage[offset] = null;
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
